package com.fire.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 邮件发送器
 * @author yuanchong
 */
public class MailUtil{

	private static Log logger = LogFactory.getLog(MailUtil.class);

	public static boolean send(String content, String subject, String host,
			String port, String sender, String password, String receiver,
			boolean needauth, String senderName, String senderAddress) {
		try {
			Session sendMailSession;
			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.port", port);
			props.put("mail.smtp.auth", String.valueOf(needauth));
			props.put("mail.smtp.connectiontimeout", "60000"); 
			props.put("mail.smtp.timeout", "60000"); 

			String account = sender.split("@")[0];
			PopupAuthenticator auth;
			auth = new PopupAuthenticator(account, password);
			sendMailSession = Session.getDefaultInstance(props, auth);

			Message newMessage = new MimeMessage(sendMailSession);
			newMessage.setFrom(new InternetAddress(sender));

			InternetAddress[] receivers = getReceiveAdd(receiver);
			newMessage.setRecipients(Message.RecipientType.TO, receivers);
			newMessage.setSubject(subject);
			newMessage.setSentDate(new Date());
			newMessage.setText(content);

			Multipart mp = new MimeMultipart();
			MimeBodyPart mbp = new MimeBodyPart();

			// 设定邮件内容的类型为 text/plain 或 text/html
			mbp.setContent(content, "text/html;charset=GB2312");
			mp.addBodyPart(mbp);
			newMessage.setContent(mp);

			if (!StringUtils.isEmpty(senderName)) {
				newMessage.setFrom(new InternetAddress(sender, senderName));

				if (!StringUtils.isEmpty(senderAddress)) {
					newMessage.setFrom(new InternetAddress(senderAddress,
							senderName));
				}
			}
			sendMailSession.getTransport("smtp").send(newMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("邮件发送失败", e);
			return false;
		}
	}
    
	public static boolean send(String content, String subject, String host,
			String port, String sender, String password, String receiver,
			String ccReceiver, boolean needauth, String senderName,
			String senderAddress) {
		try {
			Session sendMailSession;
			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.port", port);
			props.put("mail.smtp.auth", String.valueOf(needauth));
			props.put("mail.smtp.connectiontimeout", "60000"); 
			props.put("mail.smtp.timeout", "60000"); 

			String account = sender.split("@")[0];
			PopupAuthenticator auth ;
			auth = new PopupAuthenticator(account, password);
			
			sendMailSession = Session.getDefaultInstance(props, auth);

			Message newMessage = new MimeMessage(sendMailSession);
			newMessage.setFrom(new InternetAddress(sender));

			InternetAddress[] receivers = getReceiveAdd(receiver);
			newMessage.setRecipients(Message.RecipientType.TO, receivers);
			if (ccReceiver != null && !"".equals(ccReceiver)) {
				InternetAddress[] ccReceivers = getReceiveAdd(ccReceiver);
				newMessage.setRecipients(Message.RecipientType.CC, ccReceivers);
			}
			newMessage.setSubject(subject);
			newMessage.setSentDate(new Date());
			newMessage.setText(content);

			Multipart mp = new MimeMultipart();
			MimeBodyPart mbp = new MimeBodyPart();

			// 设定邮件内容的类型为 text/plain 或 text/html
			mbp.setContent(content, "text/html;charset=GB2312");
			mp.addBodyPart(mbp);
			newMessage.setContent(mp);

			if (!StringUtils.isEmpty(senderName)) {
				newMessage.setFrom(new InternetAddress(sender, senderName));

				if (!StringUtils.isEmpty(senderAddress)) {
					newMessage.setFrom(new InternetAddress(senderAddress,
							senderName));
				}
			}
			sendMailSession.getTransport("smtp").send(newMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("邮件发送失败", e);
			return false;
		}
	}
	
	/**
	 * 带附件发送
	 * @param content
	 * @param subject
	 * @param host
	 * @param port
	 * @param sender
	 * @param password
	 * @param receiver
	 * @param ccReceiver
	 * @param needauth
	 * @param senderName
	 * @param senderAddress
	 * @param attachment
	 * @return
	 */
	public static boolean send(String content, String subject, String host,
			String port, String sender, String password, String receiver,
			String ccReceiver, boolean needauth, String senderName,
			String senderAddress, File attachment) {
			InputStream in = null;
		try {
			Session sendMailSession;
			Transport transport;

			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.port", port);
			props.put("mail.smtp.auth", String.valueOf(needauth));
			props.put("mail.smtp.connectiontimeout", "60000"); 
			props.put("mail.smtp.timeout", "60000"); 

			String account = sender.split("@")[0];
			PopupAuthenticator auth ;
			auth = new PopupAuthenticator(account, password);
			sendMailSession = Session.getDefaultInstance(props, auth);

			Message newMessage = new MimeMessage(sendMailSession);
			newMessage.setFrom(new InternetAddress(sender));

			InternetAddress[] receivers = getReceiveAdd(receiver);
			newMessage.setRecipients(Message.RecipientType.TO, receivers);
			if (ccReceiver != null && !"".equals(ccReceiver)) {
				InternetAddress[] ccReceivers = getReceiveAdd(ccReceiver);
				newMessage.setRecipients(Message.RecipientType.CC, ccReceivers);
			}
			newMessage.setSubject(subject);
			newMessage.setSentDate(new Date());
			newMessage.setText(content);

			Multipart mp = new MimeMultipart();
			MimeBodyPart mbp = new MimeBodyPart();

			// 设定邮件内容的类型为 text/plain 或 text/html
			mbp.setContent(content, "text/html;charset=gb2312");
			mp.addBodyPart(mbp);

			if (!StringUtils.isEmpty(senderName)) {
				newMessage.setFrom(new InternetAddress(sender, senderName));

				if (!StringUtils.isEmpty(senderAddress)) {
					newMessage.setFrom(new InternetAddress(senderAddress,
							senderName));
				}
			}
			
			in = new FileInputStream(attachment);
			if(!attachment.isDirectory()) {
				//附件
				if(attachment.length()>0){
					mbp = new MimeBodyPart();
					DataSource ds = new ByteArrayDataSource(in, "application/octet-stream");
					mbp.setDataHandler(new DataHandler(ds));
					
					String fileName = attachment.getName();
					//附件中文名称处理
				    fileName = MimeUtility.encodeText(fileName);
					mbp.setFileName(fileName);
					mp.addBodyPart(mbp);
				}
			}
			
			
			newMessage.setContent(mp);
			sendMailSession.getTransport("smtp").send(newMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("邮件发送失败", e);
			return false;
		}finally{
			try {
				if(in != null){
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	

	public static InternetAddress[] getReceiveAdd(String receiver)
			throws Exception {
		String[] r = receiver.split(",");
		InternetAddress[] a = new InternetAddress[r.length];
		for (int i = 0; i < r.length; i++) {
			InternetAddress ad = new InternetAddress(r[i]);
			a[i] = ad;
		}
		return a;
	}

	public static void main(String[] args) {
		File file = new File("D:\\123.docx");
		MailUtil.send(
						"<html><head><meta http-equiv='Content-Type' content='text/html; charset=gb2312' /><title>hello world</title></head><body><p>888888</p><p><a href='http://www.3km.com.cn' target='_blank'>www.3km.com.cn</a> </p></body></html>",
						"中国移动官方提醒", "mmmail.aspire-tech.com", "25",
						"发件人账号", "账号密码","304097835@qq.com","yuanchong1016@163.com", true,
						"chinamobile","yuanchong@aspirecn.com",file);
	}
}